package cn.jingzhuan.element.demo.view.util.audio

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import android.view.KeyEvent


/**
 * Created by KNOX.
 */
class AudioButtonRecevier : BroadcastReceiver() {

  companion object {
    private const val TAG = "AudioButtonRecevier"
    fun handleIntent(context : Context?, intent : Intent?) : Boolean {
      if (intent == null) {
        return false
      }
      val intentAction = intent.action
      if (Intent.ACTION_MEDIA_BUTTON == intentAction) {
        val event = intent.getParcelableExtra<KeyEvent?>(Intent.EXTRA_KEY_EVENT) ?: return false
        val keycode = event.keyCode
        val action = event.action
        var command : String? = null
        if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
          command = AudioService.ACTION_PLAY_PAUSE
        }
        if (command != null) {
          if (action == KeyEvent.ACTION_DOWN) {
            context?.let { startService(it, command) }
            return true
          }
        }
      }
      return false
    }

    private fun startService(context : Context, command : String) {
      val intent = Intent(context, AudioService::class.java)
      intent.action = command
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(intent)
        Log.i(TAG, "AudioService startForeground")
      } else {
        context.startService(intent)
      }
    }
  }

  override fun onReceive(context : Context?, intent : Intent?) {
    if (handleIntent(context, intent) && isOrderedBroadcast) {
      abortBroadcast()
    }
  }

}